package com.example.demo.config;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.ibatis.io.VFS;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

public class MySpringBootVFS extends VFS{

	@Override
	public boolean isValid() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected List<String> list(URL url, String forPath) throws IOException {
		// TODO Auto-generated method stub
		ClassLoader cl = this.getClass().getClassLoader();
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
		Resource[] resources = resolver.getResources(forPath+"/**/*.class");
		List<Resource> resources1 = Arrays.asList(resources);

		List resourcePaths =new ArrayList();

		for (Resource resource: resources1) {

		resourcePaths.add(preserveSubpackageName(resource.getURI(), forPath));

		}

		return resourcePaths;
	}
	
	private static String preserveSubpackageName(final URI uri, final String rootPath) {

		final String uriStr = uri.toString();

		final int start = uriStr.indexOf(rootPath);

		return uriStr.substring(start, uriStr.length());

	}

}
